<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Model\Article;
use App\Http\Model\Category;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ArticleController extends CommonController
{
    //GET  admin/article  文章列表页面
    public function index()
    {
        //使用关联模型查询数据
        $filed = ['art_id','art_title','art_tag', 'art_description','art_time','art_editor','art_view','cate_id','art_order'];//需要查询的字段
        $data = Article::with('ext_cate')->orderBy('art_order','desc')->orderBy('art_id','desc')->paginate(15, $filed); //->skip(3)->take(5)
        //dd($data->links());

        return view('admin.article.list')->with('data',$data);
    }

    //GET admin/article/create 添加文章页面
    public function create()
    {
        $category = new Category();
        $data = $category->get_tree();

        return view('admin.article.add')->with('data',$data);
    }
    //POST admin/article/store 添加文章方法
    public function store($art_id = 0)
    {
        //判断是否操作成功
        $rs = $this->auto_save($art_id);
        if($rs === true) {
            return redirect('admin/article');
        }elseif($rs === false) {
            return back()->with('errors', '数据填充失败，请稍后重试！');
        }else {
            return back()->withErrors($rs);
        }
    }

    /**
     * 上传图片处理方法
     * @return array
     */
    public function upload()
    {
        $file = Input::file('Filedata');
        $data = ['msg' => '图片上传失败', 'errno' => 1, 'path' => ''];
        if($file->isValid()) { //上传检测有效
            //1.获取文件后缀名
            $extension = $file->getClientOriginalExtension();
            //2.生成新的文件名
            $newName = date('dHis') . mt_rand(1000,9999) . '.' . $extension;
            //3.判断目录是否存在，不存在则创建
            $real_path = 'uploads/' . date('Ym/');
            $path = base_path() . '/' . $real_path ;

            if( !file_exists( $path ) ) {
                //1.如果目录不存在
                if( !mkdir_p($path) ){
                    return $data = ['msg' => '图片上传失败,请检查 uploads 目录是否可写', 'errno' => 2, 'path' => ''];
                }
            }
            //2.目录存在，或者创建目录成功 -- 移动上传的图片位置
            if( $rs = $file->move($path, $newName) ) {
                $data = ['msg' => '图片上传成功', 'errno' => 0, 'path' => $real_path . $newName];
            }
        }
        return $data;
    }

    //GET   admin/article/{art_id}  展示单条记录页
    public function show($art_id)
    {
        return redirect('admin/article');
    }

    //GET    admin/article/{art_id}/edit 编辑展示页
    public function edit($art_id)
    {
        $category = new Category();
        $data = $category->get_tree();
        //获取编辑信息
        if( $art_info = Article::find($art_id) ) {
            return view('admin.article.edit')->with(['data' => $data, 'art_info' => $art_info]);
        }
        return redirect('admin/article');
    }

    //PUT|PATCH   admin/category/{category}  更新操作
    public function update($art_id)
    {
        //判断是否操作成功
        $rs = $this->auto_save($art_id);
        if($rs === true) {
            return redirect('admin/article');
        }elseif($rs === false) {
            return back()->with('errors', '数据填充失败，请稍后重试！');
        }else {
            return back()->withErrors($rs);
        }
    }

    //DELETE   admin/article/{id}  删除记录操作
    public function destroy($art_id)
    {

        if( $rs = Article::where('art_id', $art_id)->delete() ) {
            $data = ['msg' => '删除成功', 'errno' => 0];
        }else {
            $data = ['msg' => '删除失败', 'errno' => 2];
        }
        return $data;
    }

    /**
     * 验证插入、保存数据的方法,返回三种结果 true,false,Validator类
     * @param int $art_id 主键id
     * @return bool | object
     */
    public function auto_save($art_id = 0)
    {
        if(!is_numeric($art_id)) return back()->with('errors', '数据有误请稍后重试');
        if($input = Input::except('_token','_method')) {
            //验证规则
            $rules = [
                'cate_id' => 'required|integer',
                'art_title' => 'required',
                'art_view' => 'integer',
            ];
            //提示信息
            $messages = [
                'cate_id.required' => '分类不能为空',
                'cate_id.integer' => '分类id必须为数字',
                'art_title.required' => '文章标题不能为空',
                'art_view' => '查看次数必须为数字',
            ];

            //使用Validator验证
            $validator = Validator::make($input, $rules, $messages);
            if($validator->passes()) {
                //验证通过的操作
                if($art_id) {
                    //存在art_id 为更新操作，否则为插入
                    $rs = Article::where('art_id', $art_id)->update($input);
                }else {
                    $rs = Article::create($input);
                }
                //判断是否操作成功
                if($rs !== false) {
                    return true;
                }else {
                    return false;
                }
            }else {
                return $validator;
            }
        }
    }
}
